package service

import (
	"configuration/model"
	"database/sql"
	"encoding/json"
	"errors"
	"github.com/garyburd/redigo/redis"
)

var ErrConfigNotFound = errors.New("config 不存在")

func ConfigGet(key string) (valueData interface{}, err error) {
	var value string
	var config model.Config
	value, err = CacheGet(key)
	if err == redis.ErrNil {
		config, err = configGetItem(key)
		if err != nil {
			return
		}

		value = config.Value
		err = CacheSet(key, value)
		if err != nil {
			return
		}
	} else if err != nil {
		return
	}

	err = json.Unmarshal([]byte(value), &valueData)
	if err != nil {
		return
	}
	return
}

func ConfigAdd(key string, value string) (err error) {
	err = model.ConfigAdd(key, value)
	if err != nil {
		return
	}

	err = CacheSet(key, value)
	return
}

func ConfigEdit(key string, value string) (err error) {
	_, err = configGetItem(key)
	if err != nil {
		return
	}

	err = model.ConfigEdit(key, value)
	if err != nil {
		return
	}

	err = CacheSet(key, value)
	return
}

func ConfigDel(key string) (err error) {
	_, err = configGetItem(key)
	if err != nil {
		return
	}

	err = model.ConfigDel(key)
	if err != nil {
		return
	}

	err = CacheDel(key)
	return
}

func configGetItem(key string) (config model.Config, err error) {
	config, err = model.ConfigGet(key)
	if err == sql.ErrNoRows {
		return config, ErrConfigNotFound
	}
	return
}
